package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivedPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        //<template slot-scope="scope">
        //          <el-tag v-if="scope.row.status == 0">新建</el-tag>
        //          <el-tag type="info" v-if="scope.row.status == 1">已分配</el-tag>
        //          <el-tag type="warning" v-if="scope.row.status == 2">已领取</el-tag>
        //          <el-tag type="success" v-if="scope.row.status == 3">已完成</el-tag>
        //          <el-tag type="danger" v-if="scope.row.status == 4">有异常</el-tag>
        //        </template>
        queryWrapper.in("status",new int[]{0,1});
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //如果没有选中采购单，则新建一个
        if (purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            Date date = new Date();
            purchaseEntity.setCreateTime(date);
            purchaseEntity.setUpdateTime(date);
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseService.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        Long finalPurchaseId = purchaseId;

        List<Long> items = mergeVo.getItems();
        List<PurchaseDetailEntity> collect = items.stream().map(itemId -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(itemId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

        //合并后采购单上的日期也同步更新下
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        purchaseService.updateById(purchaseEntity);

    }

    @Override
    public void received(List<Long> ids) {
        //1、找出其中状态为新建或已分配的采购单
        //TODO 本来还应该判断是否为分配给自己啥的，先不做了
        List<PurchaseEntity> purchaseEntities = this.baseMapper.selectBatchIds(ids);
        List<PurchaseEntity> collect = purchaseEntities
                .stream()
                .filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                        || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(o -> {
                    o.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    o.setUpdateTime(new Date());

                    //TODO 采购人的Id和人名也应该更新
                    return o;
                })
                .collect(Collectors.toList());


        //2、更新采购单状态为已领取
        purchaseService.updateBatchById(collect);

        collect.forEach(item->{
            //3、关联的采购需求状态更新为“正在采购"
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
            purchaseDetailService.update(purchaseDetailEntity,
                    new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id",item.getId()));

        });
    }

    @Transactional
    @Override
    public void finishPurchase(PurchaseDoneVo purchaseDoneVo) {

        boolean success = true; //默认订单完成成功

        //1、改变订单中包含的订单需求的状态
        List<PurchaseItemVo> items = purchaseDoneVo.getItems();
        ArrayList<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        for (PurchaseItemVo purchaseItemVo : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(purchaseItemVo.getItemId());
            if (purchaseItemVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()){
                purchaseDetailEntity.setStatus(purchaseItemVo.getStatus());

                PurchaseDetailEntity byId = purchaseDetailService.getById(purchaseItemVo.getItemId());
                //已完成的订单需求入库
                wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());

            }else{
                success = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FAILED.getCode());
            }
            purchaseDetailEntities.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        //改变订单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setStatus(success?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseStatusEnum.HASERROR.getCode());

        purchaseService.updateById(purchaseEntity);


    }
}